package com.lkd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.lkd.dao.PolicyDao;
import com.lkd.entity.PolicyEntity;
import com.lkd.entity.VendingMachineEntity;
import com.lkd.entity.VmPolicyEntity;
import com.lkd.exception.LogicException;
import com.lkd.http.vo.ApplyPolicyReq;
import com.lkd.http.vo.PolicyReq;
import com.lkd.service.NodeService;
import com.lkd.service.PolicyService;
import com.lkd.service.VendingMachineService;
import com.lkd.service.VmPolicyService;
import com.lkd.vo.Pager;
import com.lkd.vo.PolicyVO;
import com.lkd.vo.VmVO;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;

@Service
public class PolicyServiceImpl extends ServiceImpl<PolicyDao,PolicyEntity> implements PolicyService {

    @Autowired
    private VmPolicyService vmPolicyService;
    @Autowired
    private VendingMachineService vendingMachineService;
    @Autowired
    private NodeService nodeService;
    @Override
    public Pager<PolicyEntity> search(Long pageIndex, Long pageSize, String policyName) {
        //判断分页数据
        if (ObjectUtils.isEmpty(pageIndex) || pageIndex < 1) {
            pageIndex = Pager.DEFAULT_PAGE_INDEX;
        }

        if (ObjectUtils.isEmpty(pageSize) || pageSize < 1) {
            pageSize = Pager.DEFAULT_PAGE_SIZE;
        }

        // 1.创建分页对象（MP）
        Page<PolicyEntity> page =  new Page<>(pageIndex,pageSize);

        // 2.构建查询对象
        LambdaQueryWrapper<PolicyEntity> queryWrapper = new LambdaQueryWrapper<>();
        if(!Strings.isNullOrEmpty(policyName)){
            queryWrapper.like(PolicyEntity::getPolicyName,policyName);
        }


        // 3.查询数据并返回
        this.page(page,queryWrapper);

        // 5.转换数据并返回 Pager对象
        return Pager.build(page);
    }

    @Override
    public boolean add(PolicyReq policyReq) {



        // 1.判断入参的各成员变量是否为空
        verifyBaseNodeMsg(policyReq);
        //2、增加策略数据并返回结果
        PolicyEntity entity = new PolicyEntity();
        //2.1复制属性
        BeanUtils.copyProperties(policyReq, entity);

        //3、数据库中增加策略信息（目前倒是不按文档的需求返回值也没啥问题）
        boolean result = this.save(entity);
        return result;
    }

    @Override
    public boolean remove(String policyId) {
        //1、判断关键数据
        if (StringUtils.isEmpty(policyId))
         {
            throw new LogicException("传入参数与接口不匹配");
        }

        // 2.判断该策略是否存在
        var qw = new LambdaQueryWrapper<PolicyEntity>();
        qw.eq(PolicyEntity::getPolicyId,policyId);
        int count =this.count(qw);
        if (count < 1) {
            throw new LogicException("策略信息不存在");
        }


        //3、调用MP删除表中数据并返回
        boolean result = this.removeById(policyId);
        return result;

    }



    @Override
    public boolean modifyPlicy(Integer policyId, PolicyReq policyReq) {
        // 1.判断入参的各成员变量是否为空
        verifyBaseNodeMsg(policyReq);
        if (StringUtils.isEmpty(policyId))
        {
            throw new LogicException("传入参数与接口不匹配");
        }
        // 2.判断该策略是否存在
        var qw = new LambdaQueryWrapper<PolicyEntity>();
        qw.eq(PolicyEntity::getPolicyId,policyId);
        int count =this.count(qw);
        if (count < 1) {
            throw new LogicException("策略信息不存在");
        }

        //2、增加策略数据并返回结果
        PolicyEntity entity = new PolicyEntity();
        //2.1复制属性
        BeanUtils.copyProperties(policyReq, entity);
        //2.2把ID复制过去
        entity.setPolicyId(policyId);
        //3、调用MP修改表中数据并返回
        boolean result = this.updateById(entity);

        return false;
    }
    //根据售货机查询策略
    @Override
    public PolicyVO getPolicy(String innerCode) {
        // 1.判断入参的各成员变量是否为空

        if (StringUtils.isEmpty(innerCode))
        {
            throw new LogicException("传入参数与接口不匹配");
        }
        // 2.判断业务数据
        val entity = vmPolicyService.searchByInnerCode(innerCode);
        if (entity==null){
            throw new LogicException("这个编号的售货机暂未采用任何策略");
        }
        //2.1复制属性
        val policyVO = new PolicyVO();
        BeanUtils.copyProperties(entity,policyVO);
        //2.2把ID复制过去
        policyVO.setVmId(entity.getInnerCode());
        return policyVO;
    }


    //取消策略
    @Override
    public boolean cancelPolicy(Long innerCode, Long policyId) {
        //1、判断关键数据
        if (ObjectUtils.isEmpty(innerCode)|| ObjectUtils.isEmpty(policyId)){
            throw new LogicException("传入参数与接口不匹配");
        }
        // 2.判断该策略是否存在
        var qw = new LambdaQueryWrapper<VmPolicyEntity>();
        qw.eq(VmPolicyEntity::getInnerCode, innerCode)
                .eq(VmPolicyEntity::getPolicyId, policyId);
        int count =vmPolicyService.count(qw);
        if (count < 1) {
            throw new LogicException("策略信息不存在");
        }
        //3、删除表中数据
        Boolean result = vmPolicyService.remove(qw);
        return result;

    }

    //获取所有策略列表
    @Override
    public ArrayList<PolicyVO> getPolicyList() {
        val list = this.list();
        ArrayList<PolicyVO>list1 = new ArrayList<>();
        for (PolicyEntity entity : list) {
            val policyVO = new PolicyVO();
            BeanUtils.copyProperties(entity, policyVO);
            list1.add(policyVO);
        }

        return list1;
    }

    @Override
    public boolean applyPolicy(ApplyPolicyReq req) {
        ArrayList<String> innerCodeList = req.getInnerCodeList();
        //1、判断关键数据
        if (innerCodeList.size()==0 || ObjectUtils.isEmpty(req.getPolicyId())){
            throw new LogicException("至少选择一个售货机，且必须选择一种策略");
        }
        //        Pager<PolicyVmVo> policyVmVoPage = new Pager<>();
//        List<PolicyVmVo> list =new ArrayList<>();

        //2、判断业务数据
        val entity = this.getById(req.getPolicyId());
        if (entity == null){
//        if (ObjectUtils.isEmpty(this.getById(req.getPolicyId())))
            throw new LogicException("该策略不存在或已被删除");
        }

        //3、实现批量添加策略操作。如果在添加途中有个别售货机被删除，那么其它存在的售货机应该不受影响的正常添加。
        ArrayList<VmPolicyEntity>list = new ArrayList<>();
        ArrayList<String> innerCodes = new ArrayList<>();
        for (String s : innerCodeList) {
            var qw = new LambdaQueryWrapper<VendingMachineEntity>();
            qw.eq(VendingMachineEntity::getInnerCode, s);
            val entity1 = vendingMachineService.getOne(qw);//从售货机列表拿到售货机
            if (entity1 == null) {
                continue;
            }

            var qw1 = new LambdaQueryWrapper<VmPolicyEntity>();
            qw1.eq(VmPolicyEntity::getInnerCode,entity1.getInnerCode());
            vmPolicyService.remove(qw1);//如果该售货机原有优惠策略，则删除。也可做成批量删除（策略不用频繁大批量切换，
            // 这样直接用update一个个改也可以）。


            //3.1复制属性
            val vmPolicyEntity = new VmPolicyEntity();
            BeanUtils.copyProperties(entity, vmPolicyEntity);
            BeanUtils.copyProperties(entity1,vmPolicyEntity);
            vmPolicyEntity.setVmId(entity1.getId());

            list.add(vmPolicyEntity);
        }
        //3.2批量添加入表
        Boolean result = vmPolicyService.saveBatch(list);

        return result;
    }

    @Override
    public Pager<VmVO> getVmList(Integer policyId, Long pageIndex, Long pageSize) {


        //  策略ID不能为空
        if(ObjectUtils.isEmpty(policyId)){
            throw new LogicException("策略ID不能为空");
        }
        //判断分页数据
        if (ObjectUtils.isEmpty(pageIndex) || pageIndex < 1) {
            pageIndex = Pager.DEFAULT_PAGE_INDEX;
        }

        if (ObjectUtils.isEmpty(pageSize) || pageSize < 1) {
            pageSize = Pager.DEFAULT_PAGE_SIZE;
        }
        // 2.创建分页对象（MP）
        Page<VmVO> page =  new Page<>(pageIndex,pageSize);
        Pager<VmVO>pager = Pager.build(page);
        val qw = new LambdaQueryWrapper<VmPolicyEntity>();
        qw.eq(VmPolicyEntity::getPolicyId,policyId)
                .select(VmPolicyEntity::getInnerCode);
        val list = vmPolicyService.listObjs(qw);
        val vmListVos = new ArrayList<VmVO>();
        for (Object o : list) {
            val vmVO = new VmVO();
            val qw1 = new LambdaQueryWrapper<VendingMachineEntity>();
            qw1.eq(VendingMachineEntity::getInnerCode,o);
           Long nodeID =  vendingMachineService.getOne(qw1).getNodeId();
            vmVO.setInnerCode(String.valueOf(o));
            vmVO.setNodeName(nodeService.getById(nodeID).getName());
            vmListVos.add(vmVO);
        }

        pager.setCurrentPageRecords(vmListVos);


        return pager;
    }


    private void verifyBaseNodeMsg(PolicyReq policyReq){
        // 1.判断关键数据()
        if (StringUtils.isEmpty(policyReq.getPolicyName())
                || ObjectUtils.isEmpty(policyReq.getDiscount())
        ) {
            throw new LogicException("传入参数与接口不匹配");
        }

    }


}


